using admin.application.Services;
using admin.core.Entities.App;
using admin.application.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;

namespace admin.api.Controllers;

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class PermissionController : ControllerBase
{
    private readonly IAppPermissionService _permissionService;
    public PermissionController(IAppPermissionService permissionService)
    {
        _permissionService = permissionService;
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] AppPermission permission)
    {
        var result = await _permissionService.CreatePermissionAsync(permission);
        return Ok(ResponseResult<AppPermission>.Ok(result, "创建权限成功"));
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Update(Guid id, [FromBody] AppPermission permission)
    {
        var result = await _permissionService.UpdatePermissionAsync(id, permission);
        return Ok(ResponseResult<AppPermission?>.Ok(result, "修改权限成功"));
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(Guid id)
    {
        try
        {
            await _permissionService.DeletePermissionAsync(id);
            return Ok(ResponseResult<object>.Ok(null, "删除权限成功"));
        }
        catch (NotFoundException ex)
        {
            return NotFound(ResponseResult<object>.Fail(ex.Message, 404));
        }
    }

    [HttpPost("{id}/enable")]
    public async Task<IActionResult> Enable(Guid id)
    {
        try
        {
            await _permissionService.EnablePermissionAsync(id);
            return Ok(ResponseResult<object>.Ok(null, "启用权限成功"));
        }
        catch (NotFoundException ex)
        {
            return NotFound(ResponseResult<object>.Fail(ex.Message, 404));
        }
    }

    [HttpPost("{id}/disable")]
    public async Task<IActionResult> Disable(Guid id)
    {
        try
        {
            await _permissionService.DisablePermissionAsync(id);
            return Ok(ResponseResult<object>.Ok(null, "禁用权限成功"));
        }
        catch (NotFoundException ex)
        {
            return NotFound(ResponseResult<object>.Fail(ex.Message, 404));
        }
    }

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var result = await _permissionService.GetAllPermissionsAsync();
        return Ok(ResponseResult<List<AppPermission>>.Ok(result, "获取权限列表成功"));
    }
} 